package com.lock.example;

import com.lock.example.lock.RedisLock;
import com.lock.example.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Homework08Application {

    //@Autowired
    //private RedisLock redisLock;
    private final static String LOCK = "redis_lock";
    private final static int EXPIRE = 3;
    private static int amount = 10;
    public static void main(String[] args) throws InterruptedException{
        SpringApplication.run(Homework08Application.class, args);
        Thread thread1 = new Thread(Homework08Application::lockTest);
        Thread thread2 = new Thread(Homework08Application::lockTest);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        Thread thread3 = new Thread(Homework08Application::lockTest);
        thread3.start();
        thread3.join();
    }

    public static void lockTest() {
        RedisLock redisLock = SpringUtil.getBean(RedisLock.class);
        System.out.println("lock test:: start sleep 10");
        long time = System.currentTimeMillis();
        try{
            if (!redisLock.tryLock(LOCK,String.valueOf(time))) {
                System.out.println("获取锁失败");
                return;
            }
            Thread.sleep(10000);
            amount -= 1;
            System.out.printf("库存减一 amount: %d\n", amount);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisLock.unlock(LOCK,String.valueOf(time));
        }
        System.out.println("lock test:: end");
    }
}
